<template>
  <div>
    <div class="tools-div">
      <el-button type="success" size="small" @click="dialogVisible = true">
        添 加
      </el-button>
    </div>

    <el-table :data="list" style="width: 100%">
      <el-table-column prop="specName" label="规格名称" />
      <el-table-column label="规格值" #default="scope">
        <div
          v-for="(item1, index1) in scope.row.specValue"
          :key="index1"
          style="padding: 5px; margin: 0;width: 100%;"
        >
          {{ item1.key }}：
          <span
            v-for="(item2, index2) in item1.valueList"
            :key="index2"
            class="div-atrr"
          >
            {{ item2 }}
          </span>
        </div>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="200" #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="handleShowEditDialog(scope.row)"
        >
          修改
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row)">
          删除
        </el-button>
      </el-table-column>
    </el-table>

    <el-pagination
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
    />
    <!-- 新增/修改 商品规格参数的对话框 -->
    <div>
      <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
        <el-form label-width="120px">
          <el-form-item label="规格名称">
            <el-input v-model="productSpec.specName" />
          </el-form-item>
          <el-form-item>
            <el-button
              size="default"
              type="success"
              @click="productSpec.specValue.push({})"
            >
              添加新规格
            </el-button>
          </el-form-item>
          <el-form-item
            label=""
            v-for="(item, index) in productSpec.specValue"
            :key="index"
          >
            <el-row>
              <el-col :span="10">
                <el-input
                  v-model="item.key"
                  placeholder="规格"
                  style="width: 90%;"
                />
              </el-col>
              <el-col :span="10">
                <el-input
                  v-model="item.valueList"
                  placeholder="规格值(如:白色,红色)"
                  style="width: 90%;"
                />
              </el-col>
              <el-col :span="4">
                <el-button
                  size="default"
                  type="danger"
                  @click="productSpec.specValue.splice(index, 1)"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item align="right">
            <el-button type="primary" @click="handleSaveOrUpdate">
              提交
            </el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  GetProductSpecPage,
  DeleteProductSpecById,
  GetProductSpecById,
  UpdateProductSpecById,
  SaveProductSpec,
} from '@/api/productSpec'
//删除按钮事件函数
const handleDelete = async row => {
  await DeleteProductSpecById(row.id)
  ElMessage.success('删除成功')
  fetchData()
}

//修改按钮事件函数: 显示修改对话框
const handleShowEditDialog = row => {
  //直接使用row回显：如果根据id查询 需要将查询到的数据转为json对象
  productSpec.value = JSON.parse(JSON.stringify(row)) //深拷贝
  dialogVisible.value = true
}
const hanldeUpdate = async () => {
  let tmp = { ...productSpec.value }
  console.log(tmp)
  //specValue的valueList表单接收的是以,分隔的字符串，需要转为json数组
  if (!tmp.specValue || tmp.specValue.length === 0) {
    ElMessage.warning('请填写规格值！！')
    return
  }
  //specValue: 是规格值的json数组 ，应该遍历它的每个json，对json对象的 valueList进行处理
  tmp.specValue.forEach(item => {
    // console.log(typeof item.valueList)
    if (typeof item.valueList === 'string')
      item.valueList = item.valueList.split(',')
  })
  console.log(tmp)
  //然后再将specValue转为json字符串
  tmp.specValue = JSON.stringify(tmp.specValue)
  await UpdateProductSpecById(tmp)
  fetchData()
  ElMessage.success('更新成功')
  dialogVisible.value = false
  productSpec.value = {
    specValue: [],
  }
}
//添加修改对话框需要的属性和函数
const dialogVisible = ref(false)
const productSpec = ref({
  specValue: [],
})
// 提交按钮事件函数
const handleSaveOrUpdate = () => {
  if (productSpec.value.id) {
    //更新
    hanldeUpdate()
  } else {
    //新增
    handleSave()
  }
}
const handleSave = async () => {
  //因为后端productSpec.specValue属性是字符串类型
  //前端提交的json数组后端接收会报错：提交前将json数组转为字符串
  let tmp = { ...productSpec.value }
  console.log(tmp)
  //specValue的valueList表单接收的是以,分隔的字符串，需要转为json数组
  if (!tmp.specValue || tmp.specValue.length === 0) {
    ElMessage.warning('请填写规格值！！')
    return
  }
  //specValue: 是规格值的json数组 ，应该遍历它的每个json，对json对象的 valueList进行处理
  tmp.specValue.forEach(item => {
    item.valueList = item.valueList.split(',')
  })
  console.log(tmp)
  //然后再将specValue转为json字符串
  tmp.specValue = JSON.stringify(tmp.specValue)
  await SaveProductSpec(tmp)
  fetchData()
  ElMessage.success('新增成功')
  dialogVisible.value = false
  productSpec.value = {
    specValue: [],
  }
}

const list = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(20)
const fetchData = async () => {
  const { data } = await GetProductSpecPage(pageNum.value, pageSize.value)
  //将后端返回的data的list中 每个对象的 specValue属性值转为json对象
  data.list.forEach(spec => {
    spec.specValue = JSON.parse(spec.specValue)
  })

  list.value = data.list
  total.value = data.total
}
onMounted(() => {
  fetchData()
})
</script>
<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
}
</style>
